package com.northwest_man.refactor_tool;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class FileUtil {
    public static StringBuilder getFileContent(final String resToFilePath) {
        return getFileContent(new File(resToFilePath));

    }

    public static StringBuilder getFileContent(final File resToFilePath) {
        final StringBuilder resToFileContent;
        try {
            resToFileContent = new StringBuilder(FileUtils.readFileToString(resToFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return resToFileContent;

    }

    public static String getFileNameWithoutSuffix(final File file) {

        return getFileNameWithoutSuffix(file, "java");
    }

    public static String getFileNameWithoutSuffix(final File file, final String suffix) {
        final Pattern pattern = Pattern.compile("([^/]+)\\." + suffix);
        final Matcher matcher = pattern.matcher(file.getAbsolutePath());
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    public static void recursionFolder(final File folder, final List<String> allFileAbsolutePath, final Handler handler) {


        if (folder.isDirectory()) {
            final File[] files = folder.listFiles();
            for (final File file : files) {
                if (file.isDirectory()) {
                    recursionFolder(file, allFileAbsolutePath, handler);
                } else {

                    handler.doHandle(file, allFileAbsolutePath);

                }
            }
        } else {
            handler.doHandle(folder, allFileAbsolutePath);

        }
    }
}
